<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="所属阶段" prop="schoolType">
          <el-select
            v-model="queryParams.schoolType"
            clearable
            placeholder="所属阶段"
            class="!w-[100px]"
            @change="selectGradeType()"
          >
            <el-option
              v-for="option in options"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属年级" prop="gradeInfoId">
          <el-select
            v-model="queryParams.gradeInfoId"
            clearable
            placeholder="所属年级"
            class="!w-[100px]"
          >
            <el-option
              v-for="option in optionsGrad"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="科目名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="科目名称"
            clearable
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <!-- <el-form-item label="" prop="id" />
        <el-form-item label="" prop="name" />
        <el-form-item
          label="阶段（1 小学 2. 初中 3. 高中)"
          prop="school_type"
        />
        <el-form-item label="所属年级id" prop="grade_info_id" />
        <el-form-item label="" prop="create_date" />
        <el-form-item label="" prop="update_date" /> -->
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          v-hasPerm="['exam:subjectinfo:add']"
          type="success"
          @click="handleOpenDialog()"
        >
          <i-ep-plus />
          新增
        </el-button>
        <el-button
          v-hasPerm="['exam:subjectinfo:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <i-ep-delete />
          删除
        </el-button>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          key="name"
          label="科目名称"
          prop="name"
          min-width="100"
        />
        <el-table-column
          key="schoolTypeName"
          label="所属阶段"
          prop="schoolTypeName"
          min-width="100"
        />
        <el-table-column
          key="gradeName"
          label="所属年级"
          prop="gradeName"
          min-width="100"
        />
        <el-table-column
          key="createTime"
          label="创建时间"
          prop="createTime"
          min-width="100"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['exam:subjectinfo:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              v-hasPerm="['exam:subjectinfo:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.current"
        v-model:limit="queryParams.size"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 科目表表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="科目名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="科目名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="所属阶段" prop="schoolType">
          <el-select
            v-model="formData.schoolType"
            clearable
            placeholder="所属阶段"
            class="!w-[100px]"
            @change="selectGradeType()"
          >
            <el-option
              v-for="option in options"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属年级" prop="schoolType">
          <el-select
            v-model="formData.gradeInfoId"
            clearable
            placeholder="所属年级"
            class="!w-[100px]"
          >
            <el-option
              v-for="option in optionsGrad"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="" prop="id" />
        <el-form-item label="" prop="name" />
        <el-form-item
          label="阶段（1 小学 2. 初中 3. 高中)"
          prop="school_type"
        />
        <el-form-item label="所属年级id" prop="grade_info_id" />
        <el-form-item label="" prop="create_date" />
        <el-form-item label="" prop="update_date" /> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确定</el-button>
          <el-button @click="handleCloseDialog">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "SubjectInfo",
  inheritAttrs: false,
});

import SubjectInfoAPI, {
  SubjectInfoForm,
  SubjectInfoPageQuery,
  SubjectInfoPageVO,
} from "@/api/subject_info";
import DictAPI from "@/api/dict";
import GradeInfoAPI, { GradeInfoPageVO } from "@/api/grade_info";

const queryFormRef = ref<ElForm>();
const dataFormRef = ref<ElForm>();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);
const options: Ref<OptionType[]> = ref([]);
const optionsGrad: Ref<GradeInfoPageVO[]> = ref([]);

const queryParams = reactive<SubjectInfoPageQuery>({
  current: 1,
  size: 10,
});

// 科目表表格数据
const pageData = ref<SubjectInfoPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 科目表表单数据
const formData = reactive<SubjectInfoForm>({});

// 科目表表单校验规则
const rules = reactive({});

/** 查询科目表 */
function handleQuery() {
  loading.value = true;
  SubjectInfoAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置科目表查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.current = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开科目表弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改科目表";
    SubjectInfoAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增科目表";
  }
}

/** 提交科目表表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        SubjectInfoAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        SubjectInfoAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭科目表弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除科目表 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      SubjectInfoAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

function selectGradeType() {
  // 根据字典id获取年级管理列表
  GradeInfoAPI.getList(queryParams).then((data) => {
    optionsGrad.value = data;
  });
}

onMounted(() => {
  // 根据字典编码获取字典项
  DictAPI.getOptions("SSJD").then((data) => {
    options.value = data;
  });

  handleQuery();
});
</script>
